package com.vogue.supplymall.shop.domain.service.impl;

import com.vogue.ssm.database.dao.BaseDao;
import com.vogue.supplymall.common.constant.ConstantBean;
import com.vogue.supplymall.common.domain.dto.QueryListResultInfo;
import com.vogue.supplymall.common.domain.dto.RelevanceInfo;
import com.vogue.supplymall.common.domain.dto.SearchInfo;
import com.vogue.supplymall.common.domain.dto.UserInfo;
import com.vogue.supplymall.common.domain.tool.MessageSourceUtils;
import com.vogue.supplymall.common.exception.DataNotFindException;
import com.vogue.supplymall.shop.common.IMemUtils;
import com.vogue.supplymall.shop.domain.dao.*;
import com.vogue.supplymall.shop.domain.model.Administrativearea;
import com.vogue.supplymall.shop.domain.model.Product;
import com.vogue.supplymall.shop.domain.model.Relevance;
import com.vogue.supplymall.shop.domain.service.AdministrativeareaService;
import com.vogue.supplymall.shop.domain.service.ProductService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;

/**
 * The type Product service.
 * 商品的service
 *
 * @Aouthor: zhangliang
 * @Date: Create in 2017-12-07
 */
@Service("productService")
public class ProductServiceImpl extends BaseServiceImpl<Product, Long> implements ProductService {

    @Resource
    private ProductDao productDao;
    @Resource
    private ProductImgDao productImgDao;
    @Resource
    private ProductPriceDao productPriceDao;
    @Resource
    private ProductAttrtypeDao productAttrtypeDao;
    @Resource
    private RelProductCategoryDao relProductCategoryDao;
    @Resource
    private ProductAttrplanDao productAttrplanDao;
    @Resource
    private ProductAttrvalueDao productAttrvalueDao;
    @Resource
    private ProductAttrplanDetailDao productAttrplanDetailDao;
    @Resource
    private RelProductCodeDao relProductCodeDao;
    @Resource
    private IMemUtils iMemUtils;
    @Autowired
    protected MessageSourceUtils messageSourceUtils;
    @Resource
    private AdministrativeareaService administrativeareaService;
    @Resource
    private RelevanceDao relevanceDao;

    /**
     * Instantiates a new Product service.
     *
     * @param baseDao the base dao
     */
    public ProductServiceImpl(BaseDao<Product, Long> baseDao) {
        super(baseDao);
    }

    @Override
    public Product findById(Long id) {
        Product product = new Product();
        if (null != id) {
            product = productDao.findById(id);
            product.setProductPrices(productPriceDao.selectByWhr(" where productid = " + product.getId()));
            product.setProductImgs(productImgDao.selectByWhr(" where productid = " + product.getId()));
        }
        return product;
    }

    @Override
    public List<Map<String, Object>> findProductById(Long id, UserInfo info) {
        if (null == id || null == info.getSyscodeid()) {
            throw new DataNotFindException(
                    messageSourceUtils.getMessage(
                            com.vogue.supplymall.common.constant.ConstantBean.GLOBAL_SYSTEM
                                    + "product", null));
        }

        List<Relevance> relevances = new ArrayList<>();
        Long watchId;
        if (null != info) {
            /* 2018/3/30 商品关注修改*/
            RelevanceInfo relevance = new RelevanceInfo();
            relevance.setTargetObjId(id);
            relevance.setType(1);
            relevance.setUserId(info.getLoginId());
            relevance.setTargetObjType(2);
            relevances = relevanceDao.findRelevance(relevance);
        }
        /* 2018/3/30 商品关注修改*/
        List<Map<String, Object>> lists = productDao.query(productDao.getSqlById(id, info.getSyscodeid()).toString());
        if (relevances.size() > 0) {
            watchId =  relevances.get(0).getId();
            lists.stream().forEach((map) -> map.put("isWatch", "1"));
            lists.stream().forEach((map) -> map.put("watchId",watchId));
        } else {
            lists.stream().forEach((map) -> map.put("isWatch", "0"));
            lists.stream().forEach((map) -> map.put("watchId", 0L));
        }
        return lists;
    }

    @Override
    public List<Map<String, Object>> findBySearchInfo(SearchInfo searchInfo) {
        if (null == searchInfo) {
            return new ArrayList<>();
        }
        Administrativearea administrativearea = administrativeareaService.get(new Long(searchInfo.getPosition()));
        if (null == administrativearea) {
            throw new DataNotFindException("");
        }
        String provinceId = administrativearea.getPid();
        searchInfo.setPositions(iMemUtils.getAreaMap(provinceId));
        List<Map<String, Object>> products = productDao.findProduct(searchInfo);
        return transformPosition(products, searchInfo.getPosition(), provinceId);
    }

    @Override
    public QueryListResultInfo findListBySearchInfo(SearchInfo searchInfo) {
        QueryListResultInfo result = new QueryListResultInfo();
        result.setRecordList(findBySearchInfo(searchInfo));
        result.setRecordCount(productDao.findProductCount(searchInfo));
        return result;
    }

    /**
     * Touch send list.
     * 根据区域省市查看可配送状态
     * 并给前端返回是否可配送
     *
     * @param products   the products
     * @param position   the Position
     * @param provinceId the province id
     * @return the list
     */
    public List<Map<String, Object>> transformPosition(List<Map<String, Object>> products, String position, String provinceId) {
        final List<Administrativearea> areas = iMemUtils.getArea(ConstantBean.AREA_LEVEL_2);
        /*匹配区域*/
        Function<String, Boolean> watchArea = (area) -> areas
                .parallelStream()
                .filter((list) -> list.getId().toString().equals(provinceId))
                .map(list -> list.getAreacode().equals(area))
                .findFirst()
                .get();
        /*匹配省*/
        Function<Object, Boolean> watchProvince = (area) -> area.toString().equals(provinceId);
        /*匹配市*/
        Function<Object, Boolean> watchCity = (area) -> area.toString().equals(position);

        for (Map<String, Object> product : products) {
            switch (product.get("sendlvl").toString()) {
                case "2":
                    product.put("sendFlag", watchArea.apply(product.get("area").toString()));
                    break;
                case "4":
                    product.put("sendFlag", watchProvince.apply(product.get("area")));
                    break;
                case "8":
                    product.put("sendFlag", watchCity.apply(product.get("area")));
                    break;
                default:
                    product.put("sendFlag", true);
                    break;
            }
        }

        return products;
    }

    @Override
    public List<Map<String, Object>> findProductUnit(SearchInfo searchInfo) {
        List<Map<String, Object>> result = productDao.findProductUnit(searchInfo);
        if (result.size() > 0) {
            if (null == searchInfo.getSyscodeid()
                    && Objects.equals(result.stream().findFirst().get().get("hiddenflag").toString(), "1")) {
                return new ArrayList<>();
            }
        }
        return result;
    }

    @Override
    public List<Product> findProductBySSM(Long sysCodeId, Long shopId, List<String> matchIds) {
        List<Product> result = null;
        if (null != sysCodeId && null != shopId && matchIds.size()>0) {
            result = productDao.findProductBySSM(sysCodeId, shopId, matchIds);
        }
        return result;
    }

    @Override
    public List<Map<String, Object>> getProductIdBySp(Long sysCodeId, String productIds) {
        List<Map<String, Object>> list = productDao.getProductIdBySp(sysCodeId, productIds);

        return list;
    }

    @Override
    public int changeProductDisabledFlag(Long sysCodeId, String productIds, boolean disabledFlag) {
        int cnt = productDao.changeProductDisabledFlag(sysCodeId, productIds, disabledFlag);
        return cnt;
    }

    @Override
    public List<Product> findProductBySS(Long sysCodeId, Long shopId) {
        List<Product> list = productDao.findProductBySS(sysCodeId, shopId);
        return list;
    }

    @Override
    public List<Map<String, Object>> findProductDUCBySP(Long sysCodeId, String productIds) {
        List<Map<String, Object>> list = productDao.findProductDUCBySP(sysCodeId, productIds);
        return list;
    }

    @Override
    public void changeNoUnitProductDU(Long sysCodeId, String productId) {
        productDao.changeNoUnitProductDU(sysCodeId, productId);

    }

    @Override
    public void changeManyUnitProductDU(Long sysCodeId, String productId) {
        productDao.changeManyUnitProductDU(sysCodeId, productId);
        productDao.changeNoUnitProductDU(sysCodeId, productId);

    }

//    @Override
//    public void saveProductCustomerRelation(String values) {
//        productDao.saveProductCustomerRelation(values);
//
//    }

    @Override
    public void delProductCustomerRelation(Long sellsyscodeid) {
        productDao.delProductCustomerRelation(sellsyscodeid);

    }

	@Override
	public List<Map<String, Object>> getProductInfoBySS(Long syscodeId,Long shopId) {
		List<Map<String, Object>> returnList=new ArrayList<>();
		Map<String, Object> paramMap=new HashMap<>();
		
		paramMap.put("syscodeId", syscodeId);
		paramMap.put("shopId", shopId);
		
		String sql=productDao.getProductInfoBySS();
		returnList=this.query0(sql, paramMap);
		
		return returnList;
	}

}
